
/*//////////////////////////////////////////////////////////////////////////////////////////////////////
    FileName:          Keyboard.c
    Author:            Tony Tan
    Version :          V1.0
    Date:              3/31 2011
    Description:       
                       Scanning keyboard status functions
    Version:      
    Function List: 
    History: 
                       Tony Tan    2011/03/31     1.0     First version  
//////////////////////////////////////////////////////////////////////////////////////////////////////*/

#include "keyboard.h"
#include "bsp.h"

volatile  KEYPKT     g_Key;

/*****************************************************************************************
Function:       void KeyBoardScan( void )
Parameter: 
                None
Return: 
                None 
Description:
	            Scan the keyboard state and filter the vibrate state
*****************************************************************************************/
void KeyBoardScan( void )
{
    UINT8 temp;
    UINT8 i;
    UINT8 state_cur;
    UINT8 state_change;

    if( g_Key.scanvalid )
    {
        g_Key.scanvalid = FALSE;

        state_cur = ~PIND;
        state_cur = (state_cur & 0xf8);
        state_cur >>= 3;                                //Get keyboard state nowtime

        state_change = state_cur ^ g_Key.state_last;    //Get the change bits

        temp = 0x01;
        for( i = 0; i < KEY_COUNT; i++ )
        {
            if( state_change & temp )                   //current key is changed?
            {
                g_Key.keydelay[i] = 0;
			}
            else
            {
                g_Key.keydelay[i] ++;
                if( g_Key.keydelay[i] > 0xf0 )
                {
                    g_Key.keydelay[i] = 0xf0;
                }

                if( g_Key.keydelay[i] == KEY_DELAY_COUNT )
                {
                    if( state_cur & temp )              //Is pressed?
                    {
                        if( !(g_Key.keyvalue & temp) )
                        {
                            g_Key.keyvalue |= temp;
                            //Set a key changed flag
                            g_Key.keychanged = TRUE;
                        }
                    }
                    else
                    {
                        if( g_Key.keyvalue & temp )
                        {
                            g_Key.keyvalue &= ~temp;
                            //Set a key changed flag
                            g_Key.keychanged = TRUE;
                        }
                    }
                }
            }	
            		
            temp <<= 1;
        }

		g_Key.state_last = state_cur;	
    }
}




